package main

import (
	"fmt"
	"time"

	"gorm.io/gorm/schema"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type Movie struct {
	gorm.Model
	Name     string
	Classify string
	AddTime  time.Time
}

// TableName 自定义表名
func (Movie) TableName() string {
	return "Hollywood"
}

// BeforeCreate 在创建数据前自动执行
func (m *Movie) BeforeCreate(tx *gorm.DB) (err error) {
	m.AddTime = time.Now()
	return
}

func main() {
	dsn := "root:root@tcp(192.168.4.111:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		// 统一给表加前缀(不能和自定义表名方法同时配置, 因为自定义表名权重更高, 会以自定义表名为准)
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: "nice_",
		},
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println("err", err)
	}

	db.AutoMigrate(&Movie{})

	db.Create(&Movie{
		Name: "Inspection",
	})
}
